package com.mmche.app.controller;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import com.framework.base.util.StringTools;
import com.framework.base.util.Tool;
import com.framework.support.domain.PageMan;
import com.framework.web.springmvc.BaseController;
import com.mmche.app.pojo.CarInfo;
import com.mmche.car.pojo.Car;
import com.mmche.car.service.CarService;
import com.mmche.common.Util;
import com.mmche.evaluate.pojo.EvaluateResult;
import com.mmche.evaluate.service.EvaluateResultService;

@Controller
public class CarController extends BaseController{

	@Resource(name="appCarService")
	private CarService carService;
	
	@Resource
	private EvaluateResultService evaluateResultService;
	
	
	/**
	 * 查询汽车信息
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("/search")
	public @ResponseBody List<CarInfo> search(@RequestBody Map<String,Object> map) throws IOException{
		int pageNo = 1;
		int pageSize = 10;
		if(map.get("pageNo") != null){
			pageNo = (Integer) map.get("pageNo");
		}
		if(map.get("pageSize") != null){
			pageSize = (Integer) map.get("pageSize");
		}
		map.put("status", Car.STATUS_SHELVES);
		PageMan pageMan = new PageMan();
		pageMan.setPageSize(pageSize);
		pageMan.setPageNo(pageNo);
		List<Car> carList = this.carService.getCarPageByMap(map, pageMan);
		//RestResponse response = new RestResponse();
		List<CarInfo> cars = new ArrayList<CarInfo>();
		if(!Tool.isEmpty(carList)){
			for(Car car :  carList){
				CarInfo info = new CarInfo(car);
				cars.add(info);
			}
		}
		return cars;
	}
	
	/**
	 * 查询估价品牌
	 * @throws IOException 
	 */
	@RequestMapping("/brand/feed")
	public @ResponseBody List<Map<String,String>> getEvaluateBrands() throws IOException{
		String result = Util.getEvaluateBrands();
		JSONArray brands = JSONArray.fromObject(result);
		List<Map<String,String>> brandList = new ArrayList<Map<String,String>>();
//		Map<String,String> emptyMap = new HashMap<String,String>();
//		emptyMap.put("text","请选择品牌");
//		emptyMap.put("brand", "");
//		brandList.add(emptyMap);
		if(!Tool.isEmpty(brands)){
			//Map<String,String> brandMap = new HashMap<String,String>();
			for(Object brand : brands){
				Map<String,String> map = new HashMap<String,String>();
				map.put("brand",brand.toString());
				map.put("firstLetter", StringTools.convert(brand.toString()));
				brandList.add(map);
				//brandMap.put(StringTools.convert(brand.toString())+ " " + brand.toString(),brand.toString());
			}
//			Map<String,String> treemap = new TreeMap<String,String>(brandMap);
//			for(Entry<String, String> brand : treemap.entrySet()){
//				Map<String,String> map = new HashMap<String,String>();
//				map.put("brand",brand.getValue());
//				map.put("text", brand.getKey());
//				brandList.add(map);
//			}
			HttpServletResponse response= this.getWebApplicationContext().getResponse();
			java.util.Date date = new java.util.Date();    
			response.setDateHeader("Last-Modified",date.getTime()); //Last-Modified:页面的最后生成时间 
			response.setDateHeader("Expires",date.getTime()+1000*60*60*24); //Expires:过时期限值 24小时
			response.setHeader("Cache-Control", "public"); //Cache-Control来控制页面的缓存与否,public:浏览器和缓存服务器都可以缓存页面信息；
		}
		return brandList;
	}
	
	/**
	 * 查询估价车系
	 * @throws IOException 
	 */
	@RequestMapping("/brand/series/feed")
	public @ResponseBody List<Map<String,String>>  getEvaluateSeries(@RequestBody Map<String,Object> paramMap) throws IOException{
		String brand = paramMap.get("brand").toString();
		logger.info("品牌:" + brand);
		if(Tool.isEmpty(brand))
			return null;
		String result = Util.getEvaluateSeries(brand);
		List<Map<String,String>> seriesList = new ArrayList<Map<String,String>>();
		JSONObject companys = JSONObject.fromObject(result);
		if(!Tool.isEmpty(companys)){
			for(Object company : companys.keySet()){
				JSONObject serieses = companys.getJSONObject(company.toString());
				for(Object series : serieses.keySet()){
					Map<String,String> map = new HashMap<String,String>();
					map.put("id", series.toString());
					map.put("company", company.toString());
					map.put("name",serieses.getString(series.toString()));
					seriesList.add(map);
				}
			}
		}
		return seriesList;
	}
	
	/**
	 * 查询估价车系
	 * @throws IOException 
	 */
	@RequestMapping("/brand/series/engine/feed")
	public @ResponseBody List<Map<String,String>>  getEvaluateEngine(@RequestBody Map<String,Object> paramMap) throws IOException{
		String seriesId = paramMap.get("seriesId").toString();
		logger.info("车系:" + seriesId);
		if(Tool.isEmpty(seriesId))
			return null;
		String result = Util.getEvaluateDisplacements(seriesId);
		List<Map<String,String>> engineList = new ArrayList<Map<String,String>>();
//		Map<String,String> emptyMap = new HashMap<String,String>();
//		emptyMap.put("text","请选择排量");
//		emptyMap.put("engine", "");
//		engineList.add(emptyMap);
		JSONArray engines = JSONArray.fromObject(result);
		if(!Tool.isEmpty(engines)){
			for(Object engine : engines){
				Map<String,String> map = new HashMap<String,String>();
				map.put("engine", engine.toString());
				map.put("text", engine.toString());
				engineList.add(map);
			}
		}
		return engineList;
	}
	
	/**
	 * 查询估价车系
	 * @throws IOException 
	 * @throws ParseException 
	 */
	@RequestMapping("/evaluate")
	public @ResponseBody EvaluateResult  evaluatel(@RequestBody Map<String,Object> paramMap) throws IOException, ParseException{
		String brand = paramMap.get("brand").toString();
		String series = paramMap.get("series").toString();
		String seriesId = paramMap.get("seriesId").toString();
		String engine = paramMap.get("engine").toString();
		boolean	at = (Boolean) paramMap.get("at");
		String miles = paramMap.get("miles").toString();
		String date = (String)paramMap.get("registerTime");
		@SuppressWarnings("deprecation")
		Date registerTime = new Date(date);
		String year = Tool.dateToString(registerTime,"yyyy");
		String month = Tool.dateToString(registerTime, "MM");
		EvaluateResult result = new EvaluateResult();
		result.setBrand(brand);
		result.setModel(series);
		result.setModelId(seriesId);
		result.setDisplacement(engine);
		result.setRegisterMonth(month);
		result.setRegisterYear(year);
		result.setTransmission(at ? "AT" : "MT");
		result.setMileage(miles);
		String evaluateResult = Util.evaluate(seriesId, engine, at, miles, year, month);
		try{
			JSONObject jsonObject = JSONObject.fromObject(evaluateResult);
			String mmchePrice = jsonObject.getString("price");
			result.setMmchePrice(mmchePrice);
			JSONObject models = jsonObject.getJSONObject("models");
			List<Map<String,String>> modelPrice = new ArrayList<Map<String,String>>();
			if(!Tool.isEmpty(models)){//有版型价格
				Map<String,Double> modelPrices = new HashMap<String,Double>();
				for(Object key : models.keySet()){
					modelPrices.put(key.toString(),models.getDouble((key.toString())));
				}
				ArrayList<Entry<String,Double>> l = new ArrayList<Entry<String,Double>>(modelPrices.entrySet());    
		        Collections.sort(l, new Comparator<Map.Entry<String, Double>>() {    
		            public int compare(Map.Entry<String, Double> o1, Map.Entry<String, Double> o2) {    
		                return o1.getValue().compareTo(o2.getValue());    
		            }    
		        });  
//				for(Entry<String,Double> e : l){
//		        	if(!Tool.isEmpty(e.getKey()) && e.getValue() != null && !Tool.isEmpty(e.getValue().toString()) && Double.parseDouble(e.getValue().toString()) > 0.0){
//			        	Map<String,String> p = new HashMap<String,String>();
//			        	p.put("model", e.getKey());
//			        	p.put("price", e.getValue().toString());
//			        	modelPrice.add(p);
//		        	}
//		        }
				TreeMap<String,Double> tMap = new TreeMap<String,Double>(modelPrices);
				for(Entry<String,Double> e : tMap.entrySet()){
		        	if(!Tool.isEmpty(e.getKey()) && e.getValue() != null && !Tool.isEmpty(e.getValue().toString()) && Double.parseDouble(e.getValue().toString()) > 0.0){
			        	Map<String,String> p = new HashMap<String,String>();
			        	p.put("model", e.getKey());
			        	p.put("price", e.getValue().toString());
			        	modelPrice.add(p);
		        	}
		        }
		        //result.setMmchePrice(String.valueOf((((int)(l.get(0).getValue()*100+0.5))/100.00)));
		        if(Tool.isEmpty(mmchePrice) || Double.parseDouble(mmchePrice) == 0){
			        result.setMmchePrice(l.get(0).getValue().toString());
			        if(l.size()>1)
			        	//result.setMmchePrice(result.getMmchePrice() + "～" + String.valueOf((((int)(l.get(l.size()-1).getValue()*100+0.5))/100.00)));
			        	result.setMmchePrice(result.getMmchePrice() + "～" + l.get(l.size()-1).getValue().toString());
			    }
				result.setModelPrice(modelPrice);
			}
			if((!Tool.isEmpty(mmchePrice) && Double.parseDouble(mmchePrice) > 0.0) || !Tool.isEmpty(modelPrice))
				result.setSuccess(true);
		}
		catch(Exception e){
			logger.error("获取评估信息出错",e);
		}
		this.evaluateResultService.saveEvaluateResult(result);
		return result;
	}
	
	/**
	 * 查询汽车信息
	 * @return
	 * @throws IOException 
	 */
	public static void main(String[] args){
		/*HttpHeaders requestHeaders = new HttpHeaders();
	    requestHeaders.setAccept(Collections.singletonList(new MediaType("application","json")));
	    Map<String,Object> body = new HashMap<String,Object>();
	    body.put("pageNo", 1);
	    body.put("pageSize", 20);
	    HttpEntity<?> requestEntity = new HttpEntity<Object>(body,requestHeaders);
		String url = "http://localhost:8080/mmche-appserver/rest/search";
	    MappingJacksonHttpMessageConverter messageConverter = new MappingJacksonHttpMessageConverter();
	    List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
	    messageConverters.add(messageConverter);
	    RestTemplate restTemplate = new RestTemplate();
	    restTemplate.setMessageConverters(messageConverters);
	    ResponseEntity<CarInfo[]> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity,CarInfo[].class,true);
	    CarInfo[] result = responseEntity.getBody();
	    System.out.print(result.length);*/
		String url = "http://localhost:9090/mmche-appserver/rest/brand/feed";
		RestTemplate restTemplate = new RestTemplate();
		restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
		System.out.println(restTemplate.getForObject(url, String.class));
	}
}

